package com.example.triprec.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;

import com.example.triprec.common.Result;
import com.example.triprec.entity.Comment;
import com.example.triprec.entity.User;
import com.example.triprec.utils.SqliteUtils;
import com.gzone.university.utils.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 评论数据访问对象
 */
@SuppressLint("Range")
public class CommentDao {

    /**
     * 添加评论
     */
    public static Result<Void> addComment(Comment comment) {
        if (comment == null || TextUtils.isEmpty(comment.getContent())
                || comment.getUserId() == null || comment.getScenicId() == null) {
            return new Result<>(false, "评论内容、用户ID或景点ID不能为空", null);
        }

        String currentTime = DateUtils.format(new Date());

        ContentValues values = new ContentValues();
        values.put("content", comment.getContent());
        values.put("user_id", comment.getUserId());
        values.put("scenic_id", comment.getScenicId());
        values.put("trip_id", comment.getTripId());
        values.put("create_time", currentTime);
        if (comment.getScore() != null) {
            values.put("score", comment.getScore());
        }

        long i = SqliteUtils.getInstance().getWritableDatabase().insert("tb_comment", null, values);
        if (i > 0) {
            return new Result<>(true, "添加评论成功", null);
        }
        return new Result<>(false, "添加评论失败", null);
    }

    /**
     * 删除评论
     */
    public static Result<Void> deleteComment(Long commentId) {
        if (commentId == null) {
            return new Result<>(false, "评论ID不能为空", null);
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().delete("tb_comment", "id=?", new String[]{String.valueOf(commentId)});
        if (i > 0) {
            return new Result<>(true, "删除评论成功", null);
        }
        return new Result<>(false, "删除评论失败", null);
    }

    /**
     * 更新评论
     */
    public static Result<Void> updateComment(Comment comment) {
        if (comment == null || comment.getId() == null || TextUtils.isEmpty(comment.getContent())) {
            return new Result<>(false, "评论ID或内容不能为空", null);
        }

        ContentValues values = new ContentValues();
        values.put("content", comment.getContent());
        if (comment.getScore() != null) {
            values.put("score", comment.getScore());
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().update("tb_comment", values, "id=?", new String[]{String.valueOf(comment.getId())});
        if (i > 0) {
            return new Result<>(true, "更新评论成功", null);
        }
        return new Result<>(false, "更新评论失败", null);
    }

    /**
     * 根据评论ID查询评论
     */
    public static Result<Comment> getCommentById(Long commentId) {
        if (commentId == null) {
            return new Result<>(false, "评论ID不能为空", null);
        }

        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_comment", null, "id=?", new String[]{String.valueOf(commentId)}, null, null, null);
        if (cursor.moveToNext()) {
            Comment comment = extractCommentFromCursor(cursor);
            cursor.close();

            // 查询评论对应的用户信息
            Result<User> userResult = UserDao.getByUserId(comment.getUserId());
            if (userResult.isSuccess()) {
                comment.setUser(userResult.getData());
            }

            return new Result<>(true, "查询成功", comment);
        }
        cursor.close();
        return new Result<>(false, "评论不存在", null);
    }

    /**
     * 根据景点ID查询评论列表
     */
    public static Result<List<Comment>> getCommentsByScenicId(Long scenicId) {
        if (scenicId == null) {
            return new Result<>(false, "景点ID不能为空", null);
        }

        List<Comment> commentList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_comment", null, "scenic_id=?", new String[]{String.valueOf(scenicId)}, null, null, "create_time DESC");

        while (cursor.moveToNext()) {
            Comment comment = extractCommentFromCursor(cursor);

            // 查询评论对应的用户信息
            Result<User> userResult = UserDao.getByUserId(comment.getUserId());
            if (userResult.isSuccess()) {
                comment.setUser(userResult.getData());
            }

            commentList.add(comment);
        }
        cursor.close();

        if (!commentList.isEmpty()) {
            return new Result<>(true, "查询成功", commentList);
        } else {
            return new Result<>(true, "暂无评论", commentList);
        }
    }

    /**
     * 根据用户ID查询评论列表
     */
    public static Result<List<Comment>> getCommentsByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        List<Comment> commentList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_comment", null, "user_id=?", new String[]{String.valueOf(userId)}, null, null, "create_time DESC");

        while (cursor.moveToNext()) {
            Comment comment = extractCommentFromCursor(cursor);
            commentList.add(comment);
        }
        cursor.close();

        if (!commentList.isEmpty()) {
            return new Result<>(true, "查询成功", commentList);
        } else {
            return new Result<>(true, "暂无评论", commentList);
        }
    }

    /**
     * 从游标中提取评论信息
     */
    private static Comment extractCommentFromCursor(Cursor cursor) {
        Comment comment = new Comment();
        comment.setId(cursor.getLong(cursor.getColumnIndex("id")));
        comment.setContent(cursor.getString(cursor.getColumnIndex("content")));
        comment.setUserId(cursor.getLong(cursor.getColumnIndex("user_id")));
        comment.setScenicId(cursor.getLong(cursor.getColumnIndex("scenic_id")));
        comment.setTripId(cursor.getLong(cursor.getColumnIndex("trip_id")));
        comment.setCreateTime(cursor.getString(cursor.getColumnIndex("create_time")));

        // score可能为空
        if (!cursor.isNull(cursor.getColumnIndex("score"))) {
            comment.setScore(cursor.getDouble(cursor.getColumnIndex("score")));
        }

        return comment;
    }

    /**
     * 获取景点平均评分
     */
    public static Result<Double> getAverageScenicScore(Long scenicId) {
        if (scenicId == null) {
            return new Result<>(false, "景点ID不能为空", null);
        }

        String sql = "SELECT AVG(score) as average_score FROM tb_comment WHERE scenic_id = ? AND score IS NOT NULL";
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().rawQuery(sql, new String[]{String.valueOf(scenicId)});

        double averageScore = 5.0;
        if (cursor.moveToFirst()) {
            if (!cursor.isNull(cursor.getColumnIndex("average_score"))) {
                averageScore = cursor.getDouble(cursor.getColumnIndex("average_score"));
            }
        }
        cursor.close();

        return new Result<>(true, "获取平均评分成功", averageScore);
    }

    public static Result<Comment> getByTripId(Long tripId) {
        if (tripId == null) {
            return new Result<>(false, "行程ID不能为空", null);
        }

        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_comment", null, "trip_id=?", new String[]{String.valueOf(tripId)}, null, null, null);
        if (cursor.moveToNext()) {
            Comment comment = extractCommentFromCursor(cursor);
            cursor.close();

            // 查询评论对应的用户信息
            Result<User> userResult = UserDao.getByUserId(comment.getUserId());
            if (userResult.isSuccess()) {
                comment.setUser(userResult.getData());
            }

            return new Result<>(true, "查询成功", comment);
        }
        cursor.close();
        return new Result<>(false, "评论不存在", null);
    }
}